<template>
  <div>
    <!-- 列表页面 -->
    <div class="container" v-if="!showEdit">
      <div class="header">
        <div class="title">设备列表</div>
        <el-button plain size="small" type="primary" @click="handleDeleteSendNum()">一键清除发送次数</el-button>

      </div>
      <!-- 表格 -->
      <el-table :data="devices" v-loading="loading">
        <el-table-column type="index" :index="indexMethod" label="序号" width="100"></el-table-column>
        <el-table-column prop="device_id" label="设备id"></el-table-column>
        <el-table-column prop="device_tag" label="设备标识"></el-table-column>
        <el-table-column prop="online" label="是否在线">
          <template #default="scope">
            <span v-if="scope.row.online == 0">离线</span>
            <span v-if="scope.row.online == 1" style="color: greenyellow">在线</span>
          </template>
        </el-table-column>
        <el-table-column prop="task_status" label="工作状态">
          <template #default="scope">
            <span v-if="(scope.row.task_status == 0)" style="color: black">空闲</span>
            <span v-if="(scope.row.task_status == 1)" style="color: green">任务执行中</span>
            <span v-if="(scope.row.task_status == 2)" style="color: red">等待任务</span>
            <span v-if="(scope.row.task_status == 200)" style="color: red">网络异常</span>
          </template>
        </el-table-column>
        <el-table-column prop="send_success_count" label="发送成功次数"></el-table-column>
        <el-table-column prop="chat_msg_tag" label="消息标签"></el-table-column>
        <el-table-column prop="time" label="最后更新时间"></el-table-column>
        <el-table-column label="操作" fixed="right" width="275">
          <template #default="scope">
            <el-button plain size="small" v-if="(scope.row.task_status == 0)" type="primary" @click="handleStartTask(scope.row.id)">开始任务</el-button>
            <el-button plain size="small" v-if="(scope.row.task_status != 0)" type="danger" @click="handleCloseTask(scope.row.id)">结束任务</el-button>
            <el-button plain size="small" type="primary" @click="handleEdit(scope.row.id)">设置消息模板</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分组信息 -->
    <el-dialog title="消息模板" :append-to-body="true" v-model="dialogFormVisible" :before-close="handleCloseDialog">
      <div style="margin-top: -25px">
        <el-select v-model="msgTag" clearable @change="setMsgTag" placeholder="请选择">
              <el-option v-for="item in msgTags" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
      </div>
      <template #footer>
        <div class="dialog-footer" style="padding-left: 5px">
          <el-button type="primary" @click="confirmSelect">确 定</el-button>
          <el-button @click="resetForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </div>

   </div>
</template>

<script>
import { onMounted,onBeforeUnmount, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import deviceModel from '@/model/device'
import messageModel from '@/model/message'


export default {

  setup() {
    const msgTag = ref('')
    let msgTags=ref([])
    const dialogFormVisible = ref(false)
    const devices = ref([])
    const editDeviceId = ref(1)
    const loading = ref(false)
    const showEdit = ref(false)

    let timeInter = null

    onMounted(() => {
      getDevices()
      getMsgTags()
      timeInter = setInterval(()=>{
        getDevices()
      },1000*20)
    })

    onBeforeUnmount(()=>{
        console.log("清除定时器")
        clearInterval(timeInter)
        timeInter = null
    })


    const getMsgTags =async()=>{
      const messages = await messageModel.getMessages()
      messages.forEach(model => {
        msgTags.value.push({value:model.id,label:model.msg_tag})
      });
    }

    const setMsgTag = async(value)=>{
      msgTags.value.forEach(model => {
        if(model.value == value){
          msgTag.value = model.label
        }
      });
    }

    const confirmSelect = async()=>{
      const res = await deviceModel.updateDeviceMsgTag(editDeviceId.value,msgTag.value)
      if (res.code < window.MAX_SUCCESS_CODE) {
        dialogFormVisible.value = false
        getDevices()
        ElMessage.success(`${res.message}`)
      }
    }

    const resetForm =() =>{
      dialogFormVisible.value = false
    }

    const getDevices = async () => {
      try {
        loading.value = true
        devices.value = await deviceModel.getDevicesOnline()
        loading.value = false
      } catch (error) {
        loading.value = false
        if (error.code === 10020) {
          devices.value = []
        }
      }
    
    }

    const handleStartTask = id => {
      ElMessageBox.confirm('是否立即开始任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await deviceModel.startTaskDevice(id)
        if (res.code < window.MAX_SUCCESS_CODE) {
          getDevices()
          ElMessage.success(`${res.message}`)
        }else{
          ElMessage.error(`${res.message}`)
        }
      })
    }

    const handleCloseTask = id => {
      ElMessageBox.confirm('是否立即结束任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await deviceModel.stopTaskDevice(id)
        if (res.code < window.MAX_SUCCESS_CODE) {
          getDevices()
          ElMessage.success(`${res.message}`)
        }else{
          ElMessage.error(`${res.message}`)
        }
      })
    }

    const handleDeleteSendNum = () => {
      ElMessageBox.confirm('是否清除所有设备发送成功次数?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        console.log(1)
        const res = await deviceModel.updateSucNum()
        console.log(4)
        if (res.code < window.MAX_SUCCESS_CODE) {
          getDevices()
          ElMessage.success(`${res.message}`)
        }else{
          ElMessage.error(`${res.message}`)
        }
      })
    }

    const editClose = () => {
      showEdit.value = false
      getDevicesOnline()
    }

    const handleEdit = id => {
      dialogFormVisible.value = true
      editDeviceId.value = id
    }

    const handleCloseDialog = () => {
      dialogFormVisible.value = false
    }


    const indexMethod = index => index + 1

   
    return {
      devices,
      loading,
      showEdit,
      editClose,
      handleStartTask,
      handleCloseTask,
      editDeviceId,
      indexMethod,
      msgTag,
      dialogFormVisible,
      handleEdit,
      handleCloseDialog,
      msgTags,
      setMsgTag,
      confirmSelect,
      resetForm,
      timeInter,
      handleDeleteSendNum
    }
  },

}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 30px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      height: 59px;
      line-height: 59px;
      color: $parent-title-color;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }
}
</style>
